package com.stationpc.dock.adapter

import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.ListAdapter
import androidx.recyclerview.widget.RecyclerView
import com.stationpc.dock.AppInfo
import com.stationpc.dock.R

class AppAdapter(
    private val onItemClick: (AppInfo) -> Unit,
    private val onItemLongClick: (AppInfo) -> Unit
) : ListAdapter<AppInfo, AppAdapter.AppViewHolder>(AppDiffCallback()) {

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): AppViewHolder {
        val view = LayoutInflater.from(parent.context)
            .inflate(R.layout.app_item, parent, false)
        return AppViewHolder(view, onItemClick, onItemLongClick)
    }

    override fun onBindViewHolder(holder: AppViewHolder, position: Int) {
        holder.bind(getItem(position))
    }

    class AppViewHolder(
        itemView: View,
        private val onItemClick: (AppInfo) -> Unit,
        private val onItemLongClick: (AppInfo) -> Unit
    ) : RecyclerView.ViewHolder(itemView) {

        private val iconView: ImageView = itemView.findViewById(R.id.appIcon)
        private val checkmarkView: ImageView = itemView.findViewById(R.id.checkmark)

        fun bind(app: AppInfo) {
            iconView.setImageDrawable(app.icon)

            checkmarkView.visibility = if (app.isSelected) View.VISIBLE else View.GONE

            itemView.setOnClickListener {
                onItemClick(app)
            }

            itemView.setOnLongClickListener {
                onItemLongClick(app)
                true
            }

            // Focus and scale handling
            itemView.setOnFocusChangeListener { view, hasFocus ->
                if (hasFocus) {
                    view.setBackgroundResource(R.drawable.focused_app_background2)
                    view.scaleX = 1.2f
                    view.scaleY = 1.2f
                } else {
                    view.setBackgroundResource(R.drawable.default_app_background2)
                    view.scaleX = 1.0f
                    view.scaleY = 1.0f
                }
            }
        }
    }

    class AppDiffCallback : DiffUtil.ItemCallback<AppInfo>() {
        override fun areItemsTheSame(oldItem: AppInfo, newItem: AppInfo): Boolean {
            return oldItem.packageName == newItem.packageName
        }

        override fun areContentsTheSame(oldItem: AppInfo, newItem: AppInfo): Boolean {
            return oldItem == newItem
        }
    }
}
